package com.training.service;

import com.training.dao.DatabaseInitializer;
import com.training.dao.ProductDao;

import java.sql.SQLException;
import java.util.*;

public class ProductService {
    private final ProductDao productDao;
    
    public ProductService() {
        this.productDao = new ProductDao();
        
        // 初始化数据库
        DatabaseInitializer initializer = new DatabaseInitializer();
        initializer.initializeDatabase();
    }

    public List<Map<String, Object>> getAllProducts() {
        try {
            return productDao.findAll();
        } catch (SQLException e) {
            throw new RuntimeException("Failed to get all products", e);
        }
    }

    public List<Map<String, Object>> getProductsWithPaginationAndSort(int page, int pageSize, String sortBy, String search) {
        try {
            int offset = (page - 1) * pageSize;
            return productDao.findWithPagination(offset, pageSize, sortBy, search);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to get products with pagination", e);
        }
    }

    public int getTotalCount(String search) {
        try {
            return productDao.getTotalCount(search);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to get total count", e);
        }
    }

    // 创建新商品
    public Map<String, Object> createProduct(String name, double price, int stock) {
        try {
            return productDao.create(name, price, stock);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to create product", e);
        }
    }

    // 根据ID获取商品
    public Map<String, Object> getProductById(int id) {
        try {
            return productDao.findById(id);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to get product by id", e);
        }
    }

    // 删除商品
    public boolean deleteProduct(int id) {
        try {
            return productDao.deleteById(id);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to delete product", e);
        }
    }

    // 更新商品
    public boolean updateProduct(int id, String name, double price, int stock) {
        try {
            return productDao.update(id, name, price, stock);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to update product", e);
        }
    }

    // 检查商品是否存在
    public boolean productExists(int id) {
        try {
            return productDao.existsById(id);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to check if product exists", e);
        }
    }
}
